import { readdirSync } from "fs";
import { join } from "path";
import { IPack } from "./IPack";
import { OppoPack } from "./oppo/OppoPack";
import { VivoPack } from "./vivo/VivoPack";
import { WxPack } from "./wx/WxPack";
import { TtPack } from "./tt/TtPack";
import { WebPack } from "./web/WebPack";

export class PackMgr {

    private static _inst: PackMgr;
    static get inst(): PackMgr {
        PackMgr._inst = PackMgr._inst || new PackMgr();
        return PackMgr._inst;
    }

    protected _packList: IPack[];
    protected _packMode: string = 'dev';

    pack(packMode = 'dev', packPlat?: string) {
        this._packList = [];
        this._packMode = packMode;

        if (!packPlat) packPlat = 'wx';// 默认平台是wx，如果是all，则将所有的发布json都跑一遍
        // 读取本地的 json 配置，然后通过配置的后缀，拿到发布的plat
        let files = readdirSync(join(process.cwd()));
        let jsonNames = files.filter(f => f.indexOf('layapp-') >= 0);
        if (packPlat == 'all') {
            jsonNames.forEach(jn => {
                let arr = jn.split('.')[0].split('-');
                let plat = arr[arr.length - 1];
                this._packList.push(this.getPack(plat, jn));
            })
        } else {
            let packPlatList = packPlat.split(',');
            console.log('pack plat:',packPlatList);
            
            packPlatList.forEach(ppl => {
                let jsonName = jsonNames.filter(jn => jn.indexOf(ppl) >= 0)[0];
                if (jsonName) {
                    // 有这个平台打包的json配置
                    this._packList.push(this.getPack(ppl, jsonName));
                }
            })
        }

        this.packNext();
    }

    getPack(packPlat: string, packJsonName: string): IPack {
        if (packPlat == 'wx') {
            return new WxPack(packJsonName)
        } else if (packPlat == 'oppo') {
            return new OppoPack(packJsonName)
        } else if (packPlat == 'vivo') {
            return new VivoPack(packJsonName)
        } else if (packPlat == 'tt') {
            return new TtPack(packJsonName)
        } else if (packPlat == 'web') {
            return new WebPack(packJsonName)
        } else if (packPlat == 'qq') {

        }
        return null;
    }

    packNext() {
        if(this._packList.length){
            let pack:IPack = this._packList.pop();
            pack.packProject(this._packMode)
        }else{
            console.log('all packages has been completed!');
            
        }

    }
}